package com.hsnr.findyourbuddy;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.hsnr.findyourbuddy.SystemException.ErrorType;

import android.content.Context;
import android.util.Log;

public abstract class Response {

    private char type;
    private String error;

    public Response(char t) {
        if (ConversationTypes.isConversationType(t)) {
            type = t;
        } else {
            throw new SystemException(ErrorType.INVALID_CONVERSATION_FORMAT);
        }
    }

    /**
     * @return the type
     */
    public char getType() {
        return type;
    }

    /**
     * @return the error
     */
    public String getError() {
        return error;
    }

    public String toJSON(Context context) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
        try {
            File outputDir = context.getFilesDir(); // context being the
                                                    // Activity pointer
            File temp = File.createTempFile("jsonResponse", ".tmp", outputDir);
            // File temp = File.createTempFile("jsonResponse", ".tmp");
            mapper.writeValue(temp, this);
            BufferedReader fr = new BufferedReader(new FileReader(temp));
            StringBuffer sb = new StringBuffer();
            String s;
            while ((s = fr.readLine()) != null) {
                sb.append(s);
                sb.append(System.getProperty("line.separator"));
            }
            fr.close();
            temp.delete();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Response fromJSON(String s, Class<?> clazz, Context context) throws JsonParseException,
            JsonMappingException {
        File outputDir = context.getCacheDir(); // context being the
        // Activity pointer
        File temp;
        try {
            temp = File.createTempFile("jsonResponse", ".tmp", outputDir);
            BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
            bw.write(s);
            bw.close();
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
            Response r = (Response) mapper.readValue(temp, clazz);
            return r;
        } catch (IOException e) {
            Log.e("FindYourBuddies", e.getMessage());
        }
        return null;
    }

}
